<script lang="ts" setup>
import type { VxeGridInstance, VxeGridProps } from "vxe-table"
import { ElMessageBox } from "element-plus"
import { computed, onMounted, reactive, ref, useTemplateRef, watch } from "vue"
import { useCompanyStore } from "@/pinia/stores/company"
import CompanyDetailModal from "./components/CompanyDetailModal.vue"
import CompanyEditModal from "./components/CompanyEditModal.vue"

defineOptions({
  // 命名当前组件
  name: "CompanyManagement"
})

const companyStore = useCompanyStore()

// #region vxe-grid
interface RowMeta {
  companyId: number
  companyName: string
  workCity: string
  companyType: string
  companyScale: string
  contactPhone: string
  contactEmail: string
  publishUserName: string
  expirationTime: string
  termPositionCount: number
  termRecruitmentCount: number
  status: string | number
  /** vxe-table 自动添加上去的属性 */
  _VXE_ID?: string
}

const xGridDom = useTemplateRef<VxeGridInstance>("xGridDom")

// 使用computed属性来响应options变化
const workCityOptions = computed(() => companyStore.options.workCityOptions)
const companyTypeOptions = computed(() => companyStore.options.companyTypeOptions)
const companyScaleOptions = computed(() => companyStore.options.companyScaleOptions)

function createFormConfigItems() {
  return [
    {
      field: "workCity",
      itemRender: {
        name: "VxeSelect",
        props: {
          placeholder: "工作城市",
          clearable: true,
          options: workCityOptions
        },
        events: {
          change: () => xGridDom.value?.commitProxy("query")
        } as { [key: string]: (...args: any[]) => any }
      }
    },
    {
      field: "companyType",
      itemRender: {
        name: "VxeSelect",
        props: {
          placeholder: "行业类型",
          clearable: true,
          options: companyTypeOptions
        },
        events: {
          change: () => xGridDom.value?.commitProxy("query")
        } as { [key: string]: (...args: any[]) => any }
      }
    },
    {
      field: "companyScale",
      itemRender: {
        name: "VxeSelect",
        props: {
          placeholder: "公司规模",
          clearable: true,
          options: companyScaleOptions
        },
        events: {
          change: () => xGridDom.value?.commitProxy("query")
        } as { [key: string]: (...args: any[]) => any }
      }
    },
    {
      field: "status",
      itemRender: {
        name: "VxeSelect",
        props: {
          placeholder: "公司状态",
          clearable: true,
          options: [
            { label: "正常", value: 1 },
            { label: "禁用", value: 0 }
          ]
        },
        events: {
          change: () => xGridDom.value?.commitProxy("query")
        } as { [key: string]: (...args: any[]) => any }
      }
    },
    {
      field: "keyword",
      itemRender: {
        name: "VxeInput",
        props: {
          placeholder: "公司名称",
          clearable: true
        },
        events: {
          keyup: (event: KeyboardEvent) => {
            if (event.key === "Enter") {
              xGridDom.value?.commitProxy("query")
            }
          }
        } as { [key: string]: (...args: any[]) => any }
      }
    },
    {
      itemRender: {
        name: "VxeButtonGroup",
        options: [
          {
            type: "submit",
            content: "查询",
            status: "primary"
          },
          {
            type: "reset",
            content: "重置",
            events: {
              click: () => {
                if (xGridDom.value) {
                  // 重置pinia中的查询参数
                  companyStore.resetQueryParams()
                  // 重置表格筛选条件
                  xGridDom.value.clearFilter()
                  // 清空表格数据
                  xGridDom.value.reloadData([])
                  // 重新查询
                  xGridDom.value.commitProxy("query")
                }
              }
            } as { [key: string]: (...args: any[]) => any }
          }
        ]
      }
    }
  ]
}

const xGridOpt: VxeGridProps = reactive({
  loading: false,
  autoResize: true,
  /** 分页配置项 */
  pagerConfig: {
    align: "right"
  },
  /** 表单配置项 */
  formConfig: {
    items: createFormConfigItems()
  },
  /** 工具栏配置 */
  toolbarConfig: {
    refresh: true,
    custom: true,
    slots: {
      buttons: "toolbar-btns"
    }
  },
  /** 列配置 */
  columns: [
    {
      type: "seq",
      title: "编号",
      width: 80,
      align: "center"
    },
    {
      field: "companyName",
      title: "公司名称",
      minWidth: 120
    },
    {
      field: "workCity",
      title: "工作城市"
    },
    {
      field: "companyType",
      title: "公司类型"
    },
    {
      field: "companyScale",
      title: "公司规模"
    },
    {
      field: "contactPhone",
      title: "联系电话"
    },
    {
      field: "contactEmail",
      title: "联系邮箱",
      visible: false
    },
    {
      field: "publishUserName",
      title: "发布人"
    },
    {
      field: "expirationTime",
      title: "到期时间",
      visible: false
    },
    {
      field: "termPositionCount",
      title: "学期岗位数"
    },
    {
      field: "termRecruitmentCount",
      title: "学期招聘人数"
    },
    {
      field: "status",
      title: "状态",
      slots: {
        default: "status-column"
      }
    },
    {
      title: "操作",
      minWidth: 100,
      fixed: "right",
      showOverflow: false,
      slots: {
        default: "row-operate"
      }
    }
  ],
  /** 数据代理配置项（基于 Promise API） */
  proxyConfig: {
    /** 启用动态序号代理 */
    seq: true,
    /** 是否代理表单 */
    form: true,
    /** 是否自动加载，默认为 true */
    autoLoad: false,
    props: {
      total: "total"
    },
    ajax: {
      query: ({ page, form }) => {
        xGridOpt.loading = true
        return new Promise((resolve) => {
          // 更新查询参数
          companyStore.updateQueryParams({
            keyword: form.keyword || "",
            workCity: form.workCity,
            companyType: form.companyType,
            companyScale: form.companyScale,
            status: form.status,
            page: page.currentPage,
            size: page.pageSize
          })

          // 加载数据并处理结果
          const callback = () => {
            xGridOpt.loading = false
            resolve({
              total: companyStore.total,
              result: companyStore.companyList
            })
          }

          companyStore.fetchCompanyList().then(callback).catch(callback)
        })
      }
    }
  }
})
// #endregion

// #region 增删改查
const crudStore = reactive({
  /** 查看详情 */
  onViewDetail: (row: RowMeta) => {
    showDetailModal.value = true
    currentCompanyId.value = row.companyId
  },
  /** 新增公司 */
  onCreateCompany: () => {
    showEditModal.value = true
    editMode.value = false
    editCompanyId.value = 0
  },
  /** 编辑公司 */
  onEditCompany: (row: RowMeta) => {
    showEditModal.value = true
    editMode.value = true
    editCompanyId.value = row.companyId
  },
  /** 删除公司 */
  onDeleteCompany: async (row: RowMeta) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除公司「${row.companyName}」吗？`,
        "删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
      const success = await companyStore.deleteCompany(row.companyId)
      if (success) {
        // 删除成功后刷新列表
        await companyStore.fetchCompanyList(true)
      }
    } catch (error) {
      // 用户取消或操作失败，不做处理
      console.error("删除公司失败:", error)
    }
  }
})

// 详情模态框控制
const showDetailModal = ref(false)
const currentCompanyId = ref(0)

// 编辑模态框控制
const showEditModal = ref(false)
const editMode = ref(false)
const editCompanyId = ref(0)

// 关闭详情模态框回调
function handleDetailModalClose() {
  currentCompanyId.value = 0
}

// 关闭编辑模态框回调
function handleEditModalClose() {
  editCompanyId.value = 0
}

// 编辑成功回调
async function handleEditSuccess() {
  // 编辑成功后刷新列表，使用 true 参数重置到第一页
  await companyStore.fetchCompanyList(true)

  // 确保表格组件更新显示最新数据
  if (xGridDom.value) {
    // 先清空表格数据，然后再提交查询，确保数据被完全刷新
    xGridDom.value.reloadData([])
    // 重新提交查询以更新表格数据
    xGridDom.value.commitProxy("query")
  }
}
// #endregion

// 监听options变化，当数据加载完成后主动刷新表格组件的表单配置
watch(
  () => [workCityOptions.value.length, companyTypeOptions.value.length, companyScaleOptions.value.length],
  () => {
    // 当选项数据加载完成后，可以通过重新设置表单配置来更新选项
    if (xGridDom.value && (workCityOptions.value.length > 0 || companyTypeOptions.value.length > 0 || companyScaleOptions.value.length > 0)) {
      // 确保formConfig存在
      if (!xGridOpt.formConfig) {
        xGridOpt.formConfig = {}
      }
      // 使用统一的表单配置生成函数
      xGridOpt.formConfig.items = createFormConfigItems()
    }
  }
)

// 初始化
onMounted(async () => {
  // 先获取选项数据
  await companyStore.fetchOptions()
  // 再加载列表数据
  xGridDom.value?.commitProxy("query")
})
</script>

<template>
  <div class="app-container">
    <!-- 表格 -->
    <vxe-grid ref="xGridDom" v-bind="xGridOpt">
      <!-- 左侧按钮列表 -->
      <template #toolbar-btns>
        <vxe-button status="primary" icon="vxe-icon-add" @click="crudStore.onCreateCompany">
          新增公司
        </vxe-button>
      </template>
      <!-- 状态列 -->
      <template #status-column="{ row, column }">
        <el-tag
          :type="row[column.field] === '正常' ? 'success' : 'danger'"
          effect="plain"
        >
          {{ row[column.field] }}
        </el-tag>
      </template>
      <!-- 操作列 -->
      <template #row-operate="{ row }">
        <el-button-group>
          <el-button link type="info" @click="crudStore.onViewDetail(row)">
            查看详情
          </el-button>
          <el-button link type="primary" @click="crudStore.onEditCompany(row)">
            编辑
          </el-button>
          <el-button link type="danger" @click="crudStore.onDeleteCompany(row)">
            删除
          </el-button>
        </el-button-group>
      </template>
    </vxe-grid>

    <!-- 公司详情模态框 -->
    <CompanyDetailModal
      v-model="showDetailModal"
      :company-id="currentCompanyId > 0 ? currentCompanyId : undefined"
      @close="handleDetailModalClose"
    />

    <CompanyEditModal
      v-model="showEditModal"
      :company-id="editMode && editCompanyId > 0 ? editCompanyId : undefined"
      :edit-mode="editMode"
      @close="handleEditModalClose"
      @success="handleEditSuccess"
    />
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}
</style>

<style scoped lang="scss">
:deep(.el-button-group) {
  display: flex;
  gap: 6px;
  align-items: center;

  .el-button {
    padding: 4px 10px;
    font-size: 12px;
    border-radius: 6px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    font-weight: 500;
    line-height: 1.4;
    letter-spacing: 0.3px;

    &:link {
      text-decoration: none;
      color: inherit;
      border: 1px solid transparent;

      &:hover {
        opacity: 1;
        text-decoration: none;
        transform: translateY(-1px);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
      }

      &:active {
        transform: translateY(0);
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      }
    }

    &:last-child {
      margin-right: 0;
    }

    &.info {
      color: #606266;

      &:hover {
        background-color: rgba(144, 147, 153, 0.15);
        color: #409eff;
        border-color: rgba(64, 158, 255, 0.3);
      }
    }

    &.primary {
      color: #409eff;

      &:hover {
        background-color: rgba(64, 158, 255, 0.15);
        color: #337ecc;
        border-color: rgba(64, 158, 255, 0.4);
      }
    }

    &.danger {
      color: #f56c6c;

      &:hover {
        background-color: rgba(245, 108, 108, 0.15);
        color: #e64340;
        border-color: rgba(245, 108, 108, 0.4);
      }
    }
  }
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  :deep(.el-button-group) {
    flex-wrap: wrap;
    gap: 4px;

    .el-button {
      padding: 3px 8px;
      font-size: 11px;
    }
  }
}
</style>
